package murgtug.mediamanager.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import murgtug.mediamanager.server.service.AudioServiceImpl;

public class AudioHttpServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private File mediaBaseDir;
	
	@Override
	public void init() throws ServletException {
		String baseDirPathname = getServletConfig().getInitParameter("media-basedir");
		if (baseDirPathname == null) {
			throw new RuntimeException("Missing 'media-basedir' servlet parameter'");
		} else {
			mediaBaseDir = new File(baseDirPathname);
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		
		int artistId = Integer.parseInt(req.getParameter("artist_id"));
		int albumId = Integer.parseInt(req.getParameter("album_id"));
		int songId = Integer.parseInt(req.getParameter("song_id"));
		
		File artistBaseDir = AudioServiceImpl.findArtistBaseDir(mediaBaseDir, 
																artistId);
		if (artistBaseDir == null) {
			resp.sendError(404, "No artist id: " + artistId);
			return;
		}
		
		File albumBaseDir = AudioServiceImpl.findAlbumBaseDir(artistBaseDir, 
															  albumId);
		if (albumBaseDir == null) {
			resp.sendError(404, "No album id: " + albumId);
			return;
		}
		
		File songFile = AudioServiceImpl.findSongFile(albumBaseDir, songId);
		if (songFile == null) {
			resp.sendError(404, "No song id: " + songId);
			return;
		}
		
		// TODO: support more than mp3's by parsing file extension and outputing 
		// the matching content-type for the file.
		resp.setContentType("audio/mpeg");
		resp.setContentLength((int) songFile.length());

		OutputStream os = resp.getOutputStream();
		InputStream is = new FileInputStream(songFile);

		int val;
		while ((val = is.read()) != -1) {
			os.write(val);
		}

		is.close();
		os.close();
	} 

}
